package iface;

import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Logs status messages
 * 
 * @author Jeff
 * 
 */
public class Logger {

    private static boolean initialized = false;
    private static FileWriter fileOut;
    private static boolean verbose = true;

    // Create the file to write to
    private static void init() {
        if (initialized)
            return;
        String file_name = "server_logfile_" + getTimestamp();
        try {
            fileOut = new FileWriter(file_name);
        } catch (IOException e) {
            System.err.print("Unable to create log file! Quitting.");
            e.printStackTrace();
            System.exit(-1);
            return;
        }
        initialized = true;
    }

    /*
     * Writes the message to file
     */
    private synchronized static void logMsg(String type, String msg) {
        init();
        String timestamp = getTimestamp();
        String formatMsg = type + " <" + timestamp + "> " + msg;
        System.out.println(formatMsg);

        try {
            fileOut.write(formatMsg + "\n");
            fileOut.flush();
        } catch (IOException e) {
            System.err.print("Unable to write message to log.");
            e.printStackTrace();
        }
    }

    /*
     * Returns a time stamp
     */
    private static String getTimestamp() {
        Date date = new Date(System.currentTimeMillis());
        DateFormat formatter = new SimpleDateFormat("MM:dd:HH:mm:ss");
        String dateFormatted = formatter.format(date);
        return dateFormatted;
    }

    /**
     * Logs an error message
     * 
     * @param msg
     *            the message to log
     */
    public static void error(String msg) {
        logMsg("ERROR", msg);
    }

    /**
     * Logs a standard message
     * 
     * @param msg
     *            the message to log
     */
    public static void log(String msg) {
        logMsg("NORMAL", msg);
    }

    /**
     * Logs a incoming ip message
     * 
     * @param clientIp
     *            the client's ip
     * @param type
     *            the type of message
     * @param msg
     *            the message to log
     */
    public static void recv(InetAddress clientIp, String type, Message msg) {
        logMsg("RECV", clientIp + " - " + type + ": " + msg);
    }

    /**
     * Logs all activity
     * 
     * @param msg
     *            the message to log
     */
    public static void verbose(String msg) {
        if (verbose)
            logMsg("VERBOSE", msg);
    }

}
